package cn.hyh.core.util;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @auther :hyh
 * @desc :
 * @date :2019/7/17
 */
public class DateUtils {
    /**
     *  判断和指定的日期相差的天数。
     * @param time
     * @param i
     * @return
     */
    public static boolean isCompareDays(Date time, int i) {
        Calendar now = Calendar.getInstance();
        Calendar paramDate = Calendar.getInstance();
        paramDate.setTime(time);
        int nowDay = now.get(Calendar.DAY_OF_YEAR);
        int paramDay = paramDate.get(Calendar.DAY_OF_YEAR);
        if (nowDay - paramDay == i) {
            return true;   //说明和现在就相差指定的天数。
        }

        return  false;
    }


    public static String countDays(Date lastLogin) {
        Calendar now = Calendar.getInstance();
        Calendar last = Calendar.getInstance();
        last.setTime(lastLogin);
        int betweendays = now.get(Calendar.DAY_OF_YEAR) - last.get(Calendar.DAY_OF_YEAR);
        if (betweendays > 0) {
            return betweendays+"天前";
        }else {
            int betweenHours = now.get(Calendar.HOUR_OF_DAY) - last.get(Calendar.HOUR_OF_DAY);
            if (betweenHours > 0) {
                return betweenHours + "小时前";
            }else {
                int betweenMin = now.get(Calendar.MINUTE) - last.get(Calendar.MINUTE);
                if (betweendays == 0) {
                    return "当前在线";
                }
                return betweenMin + "分钟前";
            }
        }


    }

    /**
     * 返回字符串对象
     * @param date
     * @return
     */
    public static String dateString(Date date) {
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        int year = instance.get(Calendar.YEAR);
        int month = instance.get(Calendar.MONTH);
        String monthStr = month + "";
        if (String.valueOf(month).length() == 1) {
            monthStr = "0" + month;
        }
        int day = instance.get(Calendar.DAY_OF_MONTH);
        String dayStr = day + "";
        if (String.valueOf(day).length() == 1) {
            dayStr = "0" + dayStr;
        }
        return String.valueOf(year) + monthStr + dayStr;
    }

    public static void main(String[] args) {
        String s = dateString(new Date());
        System.out.println(s);
    }

    public static String formatStringByParrtern(Date date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat();
        return  format.format(date);
    }
}
